package com.lyn.solitude.pluginhost.handler.andserver

import com.lyn.solitude.pluginhost.PluginManager
import com.lyn.solitude.pluginhost.andserver.RequestHandler
import com.lyn.solitude.pluginhost.andserver.RequestMethod
import com.lyn.solitude.pluginhost.andserver.annotation.RequestMapping
import com.lyn.solitude.pluginhost.andserver.upload.HttpFileUpload
import com.lyn.solitude.pluginhost.andserver.upload.HttpUploadContext
import com.lyn.solitude.pluginhost.andserver.util.HttpRequestParser
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import org.apache.httpcore.HttpEntityEnclosingRequest
import org.apache.httpcore.HttpException
import org.apache.httpcore.HttpRequest
import org.apache.httpcore.HttpResponse
import org.apache.httpcore.entity.StringEntity
import org.apache.httpcore.protocol.HttpContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * @author longyn 2024/5/26
 * @version 1.0.0
 */
class InstallPluginRequestHandler : RequestHandler {

    companion object {
        const val TAG = "UploadPluginRequestHandler"

    }

    @RequestMapping(method = [RequestMethod.POST])
    @Throws(HttpException::class, IOException::class)
    override fun handle(request: HttpRequest, response: HttpResponse, context: HttpContext) {
        if (!HttpRequestParser.isMultipartContentRequest(request)) {
            response("不能上传多文件", response)
            return
        }
        val fileItemFactory = DiskFileItemFactory(1024 * 1024, null)
        val fileUpload = HttpFileUpload(fileItemFactory)
        val fileItems =
            fileUpload.parseRequest(HttpUploadContext(request as HttpEntityEnclosingRequest))
        if (fileItems == null || fileItems.isEmpty()) {
            response("请选择文件上传", response)
            return
        }
        fileItems.forEach { fileItem ->
            val inputStream = fileItem.inputStream
            val file = File.createTempFile("upload_plugin", ".apk")
            val outputStream = FileOutputStream(file)
            var length: Int
            val buff = ByteArray(1024)
            while (inputStream.read(buff).apply { length = this } != -1) {
                outputStream.write(buff, 0, length)
            }
            outputStream.flush()
            outputStream.close()
            inputStream.close()
            val install = PluginManager.install(file.absolutePath)
            if (install) {
                response("安装成功", response)
            } else {
                response("安装失败", response)
            }
            return
        }
        response("安装失败", response)
    }


    fun response(message: String, response: HttpResponse) {
        response.setStatusCode(200)
        response.entity = StringEntity(message, "utf-8")
    }
}


